<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>07-文字-显示方位</title>
  <style>
    body {
      background-color: #000;
      text-align: center;
    }

    #c1 {
      background-color: #fff;
    }
  </style>
</head>

<body>
  <canvas id="c1" width="800" height="600"></canvas>

  <script>
    window.onload = function () {
      const oC = document.getElementById('c1')
      const gd = oC.getContext('2d')

      const startX = 400
      const startY = 300

      gd.beginPath()
      gd.moveTo(startX, startY)
      gd.lineTo(startX + 200, startY)
      gd.stroke()
      gd.beginPath()
      gd.moveTo(startX, startY)
      gd.lineTo(startX - 200, startY)
      gd.stroke()
      gd.beginPath()
      gd.moveTo(startX, startY)
      gd.lineTo(startX, startY + 200)
      gd.stroke()
      gd.beginPath()
      gd.moveTo(startX, startY)
      gd.lineTo(startX, startY - 200)
      gd.stroke()

      setTextDirection(gd, {
        x: startX,
        y: startY,
        text: 'hello world,世界城,jerry,美好',
        textAlign: 'left',
        textBaseline: 'bottom',
        font: '24px sans-serif',
        margin: 3
      })
    }

    function setTextDirection(ctx, params) {
      params = Object.assign({
        text: '',
        x: null,
        y: null,
        margin: 0,
        font: '10px sans-serif',
        color: 'black',
        style: 'fill', // 'fill' 'stroke', 填充 边框
        textAlign: 'left', // 对齐方式
        textBaseline: 'bottom' // 基线设置
      }, params);

      if (!ctx || params.text === '' || !params.x || !params.y) return

      ctx.beginPath()
      ctx.font = params.font
      ctx.fillStyle = params.color
      ctx.textAlign = params.textAlign
      ctx.textBaseline = params.textBaseline

      const texts = params.text.split(',')

      texts.forEach((text, index) => {
        const size = ctx.measureText(params.text)
        const padding = Math.ceil((size.actualBoundingBoxAscent + size.actualBoundingBoxDescent) / 7)
        const width = size.width
        let height = size.actualBoundingBoxAscent + size.actualBoundingBoxDescent
        height = params.textBaseline === 'bottom' ? -height : height
        const y = params.y + index * height
        if (params.style === 'fill') {
          ctx.fillText(text, params.x, y)
        } else {
          ctx.strokeText(text, params.x, y)
        }
      })
    }
  </script>
</body>

</html>